// import { login } from '@/api/user'

import { getProfile, login } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {},
    routes: constantRoutes
  },
  mutations: {
    setToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, newUserInfo) {
      state.userInfo = newUserInfo
    },
    setRoutes(state, newstate) {
      state.routes = [...constantRoutes, ...newstate]
    }
  },
  actions: {
    async login(context, data) {
      const token = await login(data)
      context.commit('setToken', token)
    },
    async getUserInfo(context) {
      const res = await getProfile()
      context.commit('setUserInfo', res)
      return res
    },
    logout(context) {
      context.commit('removeToken')
      context.commit('setUserInfo', {})
      resetRouter()
    }
  }
}
